﻿// -------------------------------------------------------------------------
//    @FileName         :    ProtoUtil.cpp
//    @Author           :    gaoyi
//    @Date             :    24-8-1
//    @Email            :    445267987@qq.com
//    @Module           :    ProtoUtil
//
// -------------------------------------------------------------------------

#include "ProtoUtil.h"

#if NF_PLATFORM == NF_PLATFORM_WIN
#else
#include <netinet/in.h>
#endif
#include <NFLogicCommon/CustomPacketParse.h>

#include "GameApi.h"

bool ProtoUtil::IsPacketComplete(const char* szPackBuf, int iPackLen)
{
	if (iPackLen < MSG_HEAD_LEN)
	{
		return false;
	}

	uint32_t* lens32     = (uint32_t *)szPackBuf;
	int32_t   iPacketLen = ntohl(lens32[0]);

	if (iPackLen < iPacketLen)
	{
		return false;
	}

	return true;
}

int ProtoUtil::UnpackC2AHead(char* szPackBuf, int iPackLen, proto_client2access::C2AMsgHead& oMsgHead, int& iHeadLen, int& iDataLen)
{
	uint16_t* lens   = (uint16_t *)szPackBuf;
	uint32_t* lens32 = (uint32_t *)szPackBuf;
	iDataLen         = ntohl(lens32[0]);
	iHeadLen         = ntohs(lens[2]);
	if (unlikely(!oMsgHead.ParseFromArray( szPackBuf + MSG_HEAD_LEN, iHeadLen )))
	{
		NFLogError(NF_LOG_DEFAULT, 0, " parse packet error!");
		return -1;
	}

	return 0;
}

int ProtoUtil::MakeAuthSyn(GameApi& oClient, int iUin)
{
	proto_client2access::C2A_AuthSyn oAuthSync;
	char                             szAccountId[128];
	snprintf(szAccountId, 128, "hunter_%d", iUin);
	proto_ff::AccountInfo oAccountInfo;
	oAccountInfo.set_account_id(szAccountId);
	oAccountInfo.set_account_type(::proto_ff::E_Account_Type_Local);
	oAccountInfo.set_plat_type(proto_ff::E_PLAT_ANDROID);
	oAccountInfo.SerializePartialToString(oAuthSync.mutable_account_info());

	oAuthSync.set_dhpubkey_client(oClient.m_client_dh_pubKey->BytePtr(), oClient.m_client_dh_pubKey->SizeInBytes());
	oAuthSync.set_token("Hello SailCraft");

	int iRet = oClient.Send(proto_client2access::E_C2A_AUTH_SYN, oAuthSync, oClient.GetSendSeq());
	CHECK_RET(iRet, "Send AuthSyn Failed, iRet=%d", iRet);
	return 0;
}

int ProtoUtil::MakeAuthAck(GameApi& oClient, int iUin)
{
	proto_client2access::C2A_AuthAck oAuthAck;
	std::string                      plain_text("abcde");
	oAuthAck.set_plain_text(plain_text);

	std::string cipher_text;
	oClient.aes_encrypt(plain_text, cipher_text);
	oAuthAck.set_cipher_text(cipher_text);

	::std::string strSerialbuf;
	oAuthAck.SerializePartialToString(&strSerialbuf);

	int iRet = oClient.Send(proto_client2access::E_C2A_AUTH_ACK, oAuthAck, oClient.GetSendSeq());
	CHECK_RET(iRet, "Send AuthAck Failed, iRet=%d", iRet);
	return 0;
}

int ProtoUtil::MakeLoginReq(GameApi& oClient, int iUin)
{
	return 0;
}
